package utils
{
	import flash.display.BitmapData;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	
	import manager.LoggerManager;
	
	import sunix.animationPlayer.data.FrameData;
	

	public class SpriteSheetUtil{
		public static var maxWidth:Number=1500;

		public static function genEffectBitmap(name:String, fps:int,frames:Vector.<FrameData>, path:String):void	{
			var obj:Object=genBitmap(name, fps,frames);
			var obj_xml:XML=obj.xml;
			var obj_bmd:BitmapData=obj.bmd;									
			FileUtil.writePNG(obj_bmd, path + "/" + name + ".png");
			FileUtil.writeXml(obj_xml.toXMLString(), path + "/" + name +".xml");
			LoggerManager.log("序列图及描述文件生成完毕");
		}
				
		private static function spliceBmds(bmds:Array, w:Number, h:Number):BitmapData{
			var bmd:BitmapData=new BitmapData(w, h,true, 0x00000000);
			var y:Number=0;
			for each(var _bmd:BitmapData in bmds){
				bmd.draw(_bmd, new Matrix(1,0,0,1,0,y));
				y+=_bmd.height;
			}
			
			return bmd;
		}
		
		public static function genBitmap(identifier:String, fps:int,frames:Vector.<FrameData>):Object{
			var frameno:int=1;
			var _xml:XML=<frames identifier={identifier} fps={fps}></frames>;
			var rect:Rectangle=getRect(frames);
			var bmd:BitmapData=new BitmapData(rect.width,rect.height,true,0x00000000);
			var x:Number=0;
			var y:Number=0;
			var _y:Number=0;
			var _maxh:Number=0;
			var childXml:XML;
			var tempBmd:BitmapData
			for each(var frameData:FrameData in frames){
				tempBmd = frameData.bitmapData;
				if(x+tempBmd.width<=rect.width){
					bmd.draw(tempBmd,new Matrix(1,0,0,1,x,_y));
					childXml=<frame no={frameno} x={x} y={y} w={tempBmd.width} h={tempBmd.height} ox={frameData.offsetPoint.x} oy={frameData.offsetPoint.y} />;				
					_xml.appendChild(childXml);
					frameno++;
					
					if(_maxh<tempBmd.height){
						_maxh=tempBmd.height;
					}
					x=x+tempBmd.width;
				}else{
					x=0;
					_y=_y+_maxh;
					y=y+_maxh;
					_maxh=tempBmd.height;
					
					bmd.draw(tempBmd,new Matrix(1,0,0,1,x,_y));
					childXml=<frame no={frameno} x={x} y={y} w={tempBmd.width} h={tempBmd.height} ox={frameData.offsetPoint.x} oy={frameData.offsetPoint.y} />;				
					_xml.appendChild(childXml);
					frameno++;
					
					x=x+tempBmd.width;
				}
			}
			
			return {xml:_xml,bmd:bmd};
		}
		
		public static function getRect(frames:Vector.<FrameData>):Rectangle{
			var width:Number=0;
			var height:Number=0;
			var w:Number=0;
			var h:Number=0;
			var bmd:BitmapData;
			for each(var frameData:FrameData in frames){
				bmd = frameData.bitmapData;
				if(w + bmd.width <= maxWidth){
					w = w + bmd.width;
					if(h < bmd.height){
						h = bmd.height;
					}
				}else{
					if(w>width){
						width=w;
					}
					height=height+h;
					
					w = bmd.width;
					h = bmd.height;
				}
			}
			if(width==0)width=width+w;
			height=height+h;
			return new Rectangle(0,0,width,height);
		}
	}
}